import { useEffect, useState } from 'react';
import { Button, Form, Input } from 'antd';
import { Access, useModel } from '@umijs/max'
import { editRole, getRoleInfo } from './services'
import { useRequest } from 'ahooks';
import MenuTree from '@/components/MenuTree';
import { MenuAll } from '@/services/common';

const RoleEditPage: React.FC<RoutePageProps> = (props) => {
  const [editForm] = Form.useForm()
  const { runAsync, loading } = useRequest(editRole, {manual: true})
  const { data: roleInfo, runAsync: getData, mutate } = useRequest(getRoleInfo, {manual: true})
  const [editable, setEditable] = useState(true)
  const { closeCurrentTab } = useModel('global')

  const onFinish = (formValues: any) => {
    runAsync({
      ...formValues,
      // menus: Object.keys(checked).filter(key => checked[key]),
      id: roleInfo?.data.id,
    })
    .then(() => {
      const event = new CustomEvent('refreshRoleList')
      window.dispatchEvent(event)
      closeCurrentTab('/system/roleList')
    })
  }

  useEffect(() => {
    const { id, type } = props.params
    if (id) {
      getData({roleId: id})
      .then(res => {
        const { data } = res
        editForm.setFieldsValue({
          roleName: data.roleName,
          commend: data.commend,
          menus: data.menus.map(it => it.id),
        })
      })
    } else {
      editForm.setFieldsValue({
        roleName: undefined,
        commend: undefined,
        menus: [],
      })
      mutate(undefined)
    }
    setEditable(type === 'edit')
  }, [props.params.id, props.params.type])

  return (
    <div className='container'>
      <div className="card">
        <Form form={editForm} name='editForm' labelCol={{flex: '120px'}} onFinish={onFinish}>
          <Form.Item name='roleName' label='角色名称' rules={[{required: true, message: '请输入角色名称'}]}>
            <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
          </Form.Item>
          <Form.Item name='commend' label='角色描述'>
            <Input placeholder='请输入' style={{width: 320}} disabled={!editable} />
          </Form.Item>
          <Form.Item name='menus' label='功能权限' rules={[{required: true, message: '请选择菜单'}]}>
            <MenuTree all={MenuAll.平台所有菜单} disabled={!editable} />
          </Form.Item>
          <Access accessible={editable}>
            <Form.Item label=' ' colon={false}>
              <Button type='primary' htmlType='submit' loading={loading}>提交</Button>
            </Form.Item>
          </Access>
        </Form>
      </div>
    </div>
  );
};

export default RoleEditPage;
